<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\admin\model\Admin;
use fast\Random;

/**
 * 管理员接口，暂不使用
 */
class Auth extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['register','login'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['register','login']; 

    /**
     * 注册管理员
     * 
     * @param string $username 账号
     * @param string $mobile   手机号
     * @param string $password  密码
     * @param string $event    事件
     * @param string $captcha  验证码
     * @param string $group    分组
     */
    public function register(){
        $username = $this->request->post('username');
        $mobile   = $this->request->post("mobile");
        $password = $this->request->post("password");
        $event    = $this->request->post("event");
        $event    = $event ? $event : 'register';
        $captcha  = $this->request->post("captcha");
        $group    = $this->request->post('group');

        // 校验
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if (!$username || !\think\Validate::regex($username, "^[a-zA-Z0-9_]{5,10}$")) {
            $this->error(__('账号只能是5-10位英文或数字'));
        }
        // 密码必须包含数字和字母和大小写
        if (!$password || !\think\Validate::regex($password, ".*[\d]+.*")) {
            $this->error(__('密码必须包含数字'));
        }
        if (!$password || !\think\Validate::regex($password, ".*[a-z]+.*")) {
            $this->error(__('密码必须包含小写英文字母'));
        }
        if (!$password || !\think\Validate::regex($password, ".*[A-Z]+.*")) {
            $this->error(__('密码必须包含大写英文字母'));
        }
        if (!$password || !\think\Validate::regex($password, "^[a-zA-Z0-9_!@#$%^&*()]{6,16}$")) {
            $this->error(__('密码必须是6-16位英文、数字、字母或标点'));
        }
        //过滤不允许的组别,避免越权
        if(!in_array($group,[6])){
            $this->error('选择的分组有误');
        }
        // 手机号是否已经存在
        $userinfo = Admin::getByMobile($mobile);
        if ($event == 'register' && $userinfo) {
            //已被注册
            $this->error(__('手机号已被注册'));
        } elseif (in_array($event, ['changemobile']) && $userinfo) {
            //被占用
            $this->error(__('手机号已被占用'));
        } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
            //未注册
            $this->error(__('手机号未注册'));
        }
        $userinfo = Admin::getByUsername($username);
        if ($event == 'register' && $userinfo) {
            //已被注册
            $this->error(__('用户名已被注册'));
        } 

        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {
            //注册
            if ($event == 'register') {
                $model = new Admin;
                $model->salt = Random::alnum();
                $model->password = md5(md5($password) . $model->salt);
                $model->username = $username;
                $model->mobile   = $mobile;
                $model->nickname = $username;
                $model->status  = 'hidden'; //normal hidden
                
                $model->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $result = $model->save();
                if ($result === false) {
                    $this->error($this->model->getError());
                }
    
                // 生成组信息
                $access = new \app\admin\model\AuthGroupAccess;
                $access->uid = $model->id;
                $access->group_id = $group;
                $access->save();

                $this->success(__('成功'));
            }else{
                $this->error(__('不支持的event操作类型'));
            }
        } else {
            $this->error(__('验证码不正确'));
        }
    }
    /**
     * 管理员登陆
     * 
     * @param string $username 用户名
     * @param string $mobile    手机号
     * @param string $password   密码
     * 
     */
    public  function login(){
        $username = $this->request->post('username');
        $mobile   = $this->request->post("mobile");
        $password = $this->request->post("password");
        // 手机号是否已经存在
        if(!empty($mobile)){
            $userinfo = Admin::getByMobile($mobile);
        }else if(!empty($username)){
            $userinfo = Admin::getByUsername($username);
        }else{
            $this->error(__('请输入用户名或手机号错误'));
        }
        if(empty($userinfo)){
            $this->error(__('用户名或手机号错误'));
        }
        $encrpt = md5(md5($password) . $userinfo->salt);
        if($userinfo->password != $encrpt){
            $this->error(__('密码错误'));
        }
        if($userinfo->status  == 'hidden'){
            $this->error(__('账号未审核'));
        }
        //TODO: 错误次数限制
        // $ret = $this->auth->login($account, $password);
        // if ($ret) {
        $data = ['userinfo' => $userinfo->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
        // } else {
        //     $this->error($this->auth->getError());
        // }
    }
    /**
     * 获取当前登陆管理员信息
     * 
     */
    public function getProfile()
    {
        $user = $this->auth->getUser();
        if(empty($user)){
            $this->error(__('未登陆'));
        }
        // $username = $this->request->request('username');
        // $nickname = $this->request->request('nickname');
        // $bio = $this->request->request('bio');
        // $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // if ($username) {
        //     $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
        //     if ($exists) {
        //         $this->error(__('Username already exists'));
        //     }
        //     $user->username = $username;
        // }
        // $user->nickname = $nickname;
        // $user->bio = $bio;
        // $user->avatar = $avatar;
        // $user->save();
        // $this->success();
        return json(['success'=>true,'data'=>$user]);
    }
}